package com.jblog.controller.directive;

import static com.jblog.Constants.Encoding.UTF8;
import static com.jblog.Constants.Template.TPL_STYLE_LIST;
import static com.jblog.Constants.Template.TPL_SUFFIX;
import static com.jblog.common.web.freemarker.DirectiveUtils.OUT_LIST;
import static com.jblog.common.web.freemarker.DirectiveUtils.OUT_PAGINATION;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.jblog.common.page.Pagination;
import com.jblog.common.web.FrontUtils;
import com.jblog.common.web.freemarker.DirectiveUtils;
import com.jblog.controller.directive.abs.AbstractCommentDirective;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@SuppressWarnings({"unchecked", "rawtypes"})
public class CommentPageDirective extends AbstractCommentDirective {

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
            TemplateDirectiveBody body) throws TemplateException, IOException {
        
        Pagination page = (Pagination) super.getData(params, env);
        
        Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
        paramWrap.put(OUT_PAGINATION, DEFAULT_WRAPPER.wrap(page));
        paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(page.getDatas()));
        Map<String, TemplateModel> origMap = DirectiveUtils
                .addParamsToVariable(env, paramWrap);
        
        env.include(TPL_STYLE_LIST + DirectiveUtils.getStyleList(params) + TPL_SUFFIX, UTF8, true);
        FrontUtils.includePagination(params, env);
        
        DirectiveUtils.removeParamsFromVariable(env, params, origMap);
    }

    @Override
    protected boolean isPage() {
        return true;
    }
}
